/*
    Copyright (C) 2008-2009 Dmitry Gusev <dmitry.gusev@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

 */

package dmitrygusev.web4konverta.mobile;

import java.io.UnsupportedEncodingException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

/**
 *
 * @author dmitrygusev
 */
public class AppConfig {
    public static final String RECORD_STORE_NAME = "AppConfig";
    
    private String accountName = "";
    private String accountPassword = "";
    private String personId = "";

    public AppConfig(String accountName, String accountPassword, String personId) {
        this.accountName = accountName;
        this.accountPassword = accountPassword;
        this.personId = personId;
    }
    
    public String getAccountName() {
        return accountName;
    }

    public String getAccountPassword() {
        return accountPassword;
    }

    public String getPersonId() {
        return personId;
    }

    public boolean isAccountInfoAvailable()
    {
        return Utils.areBothSpecified(getAccountName(), getAccountPassword());
    }
    
    public void updateAccountInfo(String login, String password) 
            throws RecordStoreException
    {
        this.accountName = login;
        this.accountPassword = password;
        
        writeAppConfig(this);
    }

    void resetAccountPassword() {
        this.accountPassword = "";
    }

    void updatePersonId(String personId) throws RecordStoreException {
        this.personId = personId;
        
        writeAppConfig(this);
    }
    
    private static RecordStore openRecordStore() throws RecordStoreException {
        return RecordStore.openRecordStore(RECORD_STORE_NAME, true);
    }
    
    public static AppConfig readAppConfig() throws RecordStoreException {
        RecordStore rs = null;
        
        try {
            rs = openRecordStore();

            return rs.getNumRecords() == 0
                    ? new AppConfig("", "", "")
                    : new AppConfig(
                                    readString(rs, 1),
                                    readString(rs, 2),
                                    readString(rs, 3));
        }
        finally {
            if (rs != null) {
                rs.closeRecordStore();
                rs = null;
            }
        }
    }
    
    private static void writeAppConfig(AppConfig appConfig)
            throws RecordStoreException
    {
        RecordStore rs = null;
        
        try {
            rs = openRecordStore();
            
            if (rs.getNumRecords() != 0 && rs.getNumRecords() != 3) {
                //  RecordStore corrupted
                rs.closeRecordStore();
                
                rs = null;
                
                RecordStore.deleteRecordStore(RECORD_STORE_NAME);
                
                rs = openRecordStore();
            }
            
            if (rs.getNumRecords() == 0) {
                addString(rs, appConfig.getAccountName());
                addString(rs, appConfig.getAccountPassword());
                addString(rs, appConfig.getPersonId());
            }
            else if (rs.getNumRecords() == 3) {
                updateString(rs, 1, appConfig.getAccountName());
                updateString(rs, 2, appConfig.getAccountPassword());
                updateString(rs, 3, appConfig.getPersonId());
            }
        }
        finally {
            if (rs != null) {
                rs.closeRecordStore();
                rs = null;
            }
        }
    }
    
    private static void addString(RecordStore rs, final String value)
        throws RecordStoreException
    {
        byte[] bytes;
        try {
            bytes = value.getBytes("UTF-8");
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex.getMessage());
        }
        rs.addRecord(bytes, 0, bytes.length);
    }

    private static void updateString(RecordStore rs, int recordId,
            final String newValue) throws RecordStoreException
    {
        byte[] bytes;
        try {
            bytes = newValue.getBytes("UTF-8");
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex.getMessage());
        }

        rs.setRecord(recordId, bytes, 0, bytes.length);
    }

    private static String readString(RecordStore rs, int recordId)
            throws RecordStoreException
    {
        byte[] value = rs.getRecord(recordId);

        if (value == null || value.length == 0) {
            return "";
        }

        try {
            return new String(value, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex.getMessage());
        }
    }

}
